export function useReadStream () {
  async function handleStreamResponse (response, onMessage) {
    const reader = response.body.getReader()
    const decoder = new TextDecoder()
    let done = false
    let buffer = ''
    while (!done) {
      const { value, done: isDone } = await reader.read()
      done = isDone
      buffer += decoder.decode(value, { stream: true })
      if (!buffer.includes('\n')) continue
      const messages = buffer.split('\n')
      for (const message of messages) {
        const jsonStr = message.replace(/^\s*data: \s*/, '').trim()
        if (jsonStr !== '[DONE]') {
          if (jsonStr === '') continue
          try {
            const jsonData = JSON.parse(jsonStr)
            onMessage(jsonData)
          } catch (error) {
            console.error('Error parsing JSON:', error)
          }
        } else {
          done = true
        }
      }
      buffer = ''
    }
  }
  return { handleStreamResponse }
}
